package com.dtguai.admin.web.sys.oauth2;

import com.dtguai.admin.common.error.ErrorCode;
import com.dtguai.admin.web.sys.model.SysAdminToken;
import com.dtguai.admin.web.sys.model.SysDefAdmin;
import com.dtguai.admin.web.sys.service.ShiroService;
import com.dtguai.admin.web.sys.service.impl.SysUserTokenServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.Set;

/**
 * 认证
 *
 * @author guo
 */
@Component
public class Oauth2Realm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private ShiroService shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysDefAdmin admin = (SysDefAdmin) principals.getPrimaryPrincipal();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(admin.getId());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        SysAdminToken tokenEntity = Optional.ofNullable(shiroService.getAdminToken(accessToken))
                .orElseThrow(() -> new IncorrectCredentialsException(ErrorCode.SC_UNAUTHORIZED.getMessage()));
        //token失效 超过 过期时间+刷新时间
        if (tokenEntity.getExpireTime().getTime() + SysUserTokenServiceImpl.REFRESH_EXPIRE < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        } else if (tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            //刷新token时间
            shiroService.refreshTokenTime(tokenEntity);
        }

        //查询用户信息
        SysDefAdmin user = shiroService.queryUser(tokenEntity.getAdminId());
        //账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
